import React, { useState, useEffect } from 'react';
import { useHistory } from "react-router-dom";
import { Form, Input, Button, Checkbox } from 'antd';


export default function Signup() {
  const [signup, setSignup] = useState(false);
  // const [btnsEnabled, setBtnsEnabled] = useState(false);
  let btnsEnabled = false;

  let axios = require('axios');
  let user = '';
  let pass = '';
  let check_pass = '';
  let history = useHistory();

  const showMessage = () => {
    alert('两次密码输入不一致')
  }

  useEffect(() => {
    if (signup) {
      history.push("/login")
    }
  });
  const handleSignup = () => {
    const data = {
      "user": user,
      "password": pass
    }
    // 判断两次密码否一致，需要客户端判断
    if(pass != check_pass)
    {
      //如果两次不一致，就不执行ajax了
      return;
    }

    axios.post(`https://c958fd37-19ce-4279-9844-460504d1a85e.bspapp.com//http/register`, data)
      .then(function (response) {
        console.log(response.data.code);
        
        if (check_pass == pass) {
          setSignup(response.data.code == 200)
        } else {
          showMessage()
        }
      })
  }

  return (
    <div>
      <Form name="basic"
        labelCol={{
          span: 5,
        }}
        wrapperCol={{
          span: 12,
        }}
        initialValues={{
          remember: true,
        }}

      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            {
              required: true,
              message: '请输入用户名!',
            },
          ]}
          onChange={e => user = e.target.value}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
          ]}
          onChange={e => pass = e.target.value}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          label="密码"
          name="check_password"
          rules={[
            {
              required: true,
              message: '请再次输入密码',
            },
          ]}
          onChange={e => check_pass = e.target.value}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="remember"
          valuePropName="checked"
          wrapperCol={{
            offset: 5,
            span: 12,
          }}
        >
          <Checkbox>Remember me</Checkbox>
          <Checkbox><a href=":;">同意须知</a></Checkbox>
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 5,
            span: 12,
          }}
        >
          <Button disabled={btnsEnabled} type="primary" htmlType="submit" disabled={btnsEnabled} onClick={handleSignup}>
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
